package com.kmxd.ams.controller.archive;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kmxd.ams.client.archive.IArchiveSealSvc;
import com.kmxd.ams.client.archive.dto.*;
import com.kmxd.ams.client.archive.vo.ArchiveSealListVO;
import com.kmxd.ams.client.archive.vo.ArchiveSealVO;
import com.kmxd.ams.core.common.enums.LogLevelEnum;
import com.kmxd.ams.core.common.enums.LogTypeEnum;
import com.kmxd.ams.core.log.annotation.AutoLog;
import com.kmxd.ams.core.result.R;
import com.kmxd.ams.core.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 档号章设置 前端控制器
 *
 * @author ZuoLG
 * @since 2023-09-11
 */
@Slf4j
@RestController
@Tag(name = "档号章设置")
@RequestMapping("/archive/archiveSeal")
@AllArgsConstructor
public class ArchiveSealCtl {

  private final IArchiveSealSvc archiveSealSvc;

  /** 分页查询 */
  @Operation(summary = "分页查询")
  @RequestMapping("/selectPage")
  @AutoLog(module = "档号章设置", title = "分页查询")
  public R<Page<ArchiveSealListVO>> selectPage(Page reqPage, ArchiveSealQueryDTO req) {
    return R.success(archiveSealSvc.selectPage(reqPage, req));
  }

  /** 列表查询 */
  @Operation(summary = "列表查询")
  @RequestMapping("/selectList")
  @AutoLog(module = "档号章设置", title = "列表查询")
  public R<List<ArchiveSealListVO>> selectList(ArchiveSealQueryDTO req) {
    return R.success(archiveSealSvc.selectList(req));
  }

  /** 新增 */
  @Operation(summary = "新增")
  @PostMapping("/add")
  @AutoLog(module = "档号章设置", title = "新增")
  public R<Void> add(@Validated @RequestBody ArchiveSealAddDTO req) {
    req.setComId(ObjectUtil.isEmpty(req.getComId()) ? SecurityUtil.getCropId() : req.getComId());
    req.setFondsId(
        ObjectUtil.isEmpty(req.getFondsId()) ? SecurityUtil.getFondsId() : req.getFondsId());
    archiveSealSvc.add(req);
    return R.success();
  }

  /** 修改 */
  @Operation(summary = "修改")
  @PostMapping("/edit")
  @AutoLog(module = "档号章设置", title = "修改")
  public R<Void> edit(@Validated @RequestBody ArchiveSealEditDTO req) {
    req.setComId(ObjectUtil.isEmpty(req.getComId()) ? SecurityUtil.getCropId() : req.getComId());
    req.setFondsId(
        ObjectUtil.isEmpty(req.getFondsId()) ? SecurityUtil.getFondsId() : req.getFondsId());
    archiveSealSvc.edit(req);
    return R.success();
  }

  /** 删除 */
  @Operation(summary = "删除")
  @PostMapping("/remove")
  @AutoLog(module = "档号章设置", title = "删除")
  public R<Void> remove(@RequestParam String ids) {
    archiveSealSvc.remove(ids);
    return R.success();
  }

  /** 查看 */
  @Operation(summary = "查看")
  @RequestMapping("/view")
  @AutoLog(module = "档号章设置", title = "查看")
  public R<ArchiveSealVO> view(@RequestBody ArchSealDTO req) {
    return R.success(archiveSealSvc.view(req));
  }

  /** 下载电子签章文件 */
  @Operation(summary = "下载电子签章文件")
  @RequestMapping("/downSeal")
  @AutoLog(
      module = "文件下载",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "文件下载",
      opType = "下载")
  @SneakyThrows
  public void downSeal(@RequestBody ArchSealDTO req, HttpServletResponse response) {
    // 电子文件ID
    File file = archiveSealSvc.getSeal(req);
    response.reset();
    if (ObjectUtil.isEmpty(file)) {
      try (ServletOutputStream out = response.getOutputStream()) {
        R r = R.fail("当前下载文件为空！");
        String json = JSONUtil.toJsonStr(r);
        IoUtil.write(out, true, json.getBytes(StandardCharsets.UTF_8));
      } catch (IOException e) {
        log.error("{} 文件下载失败", file, e);
      }
    } else {
      response.setContentType("application/octet-stream;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
      response.setHeader(
          "Content-Disposition",
          "attachment; filename="
              + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.name()));
      response.addHeader("Content-Length", String.valueOf(file.length()));
      try (ServletOutputStream out = response.getOutputStream()) {
        IoUtil.write(out, true, FileUtil.readBytes(file));
      } catch (IOException e) {
        log.error("{} 文件下载失败", file, e);
      }
    }
  }

  /** 批量导出归档章 */
  @Operation(summary = "批量导出归档章")
  @RequestMapping("/exportSealFile")
  @AutoLog(
      module = "文件下载",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "批量导出归档章",
      opType = "导出")
  @SneakyThrows
  public void exportSealFile(@RequestBody ExportSealDTO req, HttpServletResponse response) {
    // 电子文件ID
    File file = archiveSealSvc.exportSealFile(req);
    response.reset();
    if (ObjectUtil.isEmpty(file)) {
      try (ServletOutputStream out = response.getOutputStream()) {
        R r = R.fail("当前下载文件为空！");
        String json = JSONUtil.toJsonStr(r);
        IoUtil.write(out, true, json.getBytes(StandardCharsets.UTF_8));
      } catch (IOException e) {
        log.error("{} 文件下载失败", file, e);
      }
    } else {
      response.setContentType("application/octet-stream;charset=UTF-8");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
      response.setHeader(
          "Content-Disposition",
          "attachment; filename="
              + URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.name()));
      response.addHeader("Content-Length", String.valueOf(file.length()));
      try (ServletOutputStream out = response.getOutputStream()) {
        IoUtil.write(out, true, FileUtil.readBytes(file));
      } catch (IOException e) {
        log.error("{} 文件下载失败", file, e);
      }
    }
  }
}
